package com.missilike.biz.impl;

import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.missilike.biz.IMilMessagePushService;
import com.missilike.core.utils.JPushUtils;
import com.missilike.repository.entity.MilMessagePush;
import com.missilike.repository.mapper.MilMessagePushMapper;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 主动消息推送 服务实现类
 * </p>
 *
 * @author kin
 * @since 2019-01-02
 */
@Service
public class MilMessagePushServiceImpl extends ServiceImpl<MilMessagePushMapper, MilMessagePush> implements IMilMessagePushService {

    private final JPushUtils jPushUtils;

    @Autowired
    public MilMessagePushServiceImpl(JPushUtils jPushUtils) {
        this.jPushUtils = jPushUtils;
    }

    @Async
    @Override
    public void messagePush(MilMessagePush milMessagePush) {
        Map<String, String> extrasMap = JSONObject.parseObject(milMessagePush.getExtras(), new TypeReference<Map<String, String>>() {
        });
        if (MapUtils.isEmpty(extrasMap)) {
            extrasMap = Maps.newHashMap();
        }
        extrasMap.put("type", milMessagePush.getType().toString());
        boolean pushResult = jPushUtils.sendPushAllNotification(
                milMessagePush.getTitle(),
                milMessagePush.getContent(),
                extrasMap
        );

        MilMessagePush update = new MilMessagePush();
        update.setId(milMessagePush.getId());
        update.setStatus(pushResult ? 0 : 1);
        baseMapper.updateById(update);
    }
}
